package com.carkeeper.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carkeeper.dto.CarDTO;
import com.carkeeper.pojo.CarPO;
import com.carkeeper.service.CarService;
import com.carkeeper.vo.CarQueryParamVo;
import com.carkeeper.vo.Pager;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 车辆信息控制器
 */
@RestController
@RequestMapping("/car")
public class CarController {
    @Autowired
    private CarService carService;

    /**
     * 获取车辆分页数据
     *
     * @param paramVo 查询条件
     * @return 车辆分页数据
     */
    @PostMapping("/page")
    public Pager<CarPO> findByPage(@RequestBody CarQueryParamVo paramVo) {
        Page<CarPO> carPOPage = carService.findByPage(paramVo);
        return new Pager<>(carPOPage.getTotal(), carPOPage.getSize(), carPOPage.getPages(), carPOPage.getCurrent(), carPOPage.getRecords());
    }

    /**
     * 根据id获取车辆详情
     *
     * @param id 车辆id
     * @return 车辆详情
     */
    @GetMapping("/{id}")
    public CarDTO findById(@PathVariable Long id) {
        CarDTO dto = new CarDTO();
        CarPO po = carService.findById(id);
        if (po != null) {
            BeanUtils.copyProperties(po, dto);
        }
        return dto;
    }

    /**
     * 根据车牌号获取车辆信息
     *
     * @param dto 车牌号
     * @return 车辆信息
     */
    @PostMapping("/code")
    public CarDTO findByCode(@RequestBody CarDTO dto) {
        CarPO po = carService.findByCode(dto.getCode());
        if (po != null) {
            BeanUtils.copyProperties(po, dto);
        }
        return dto;
    }

    /**
     * 删除车辆
     *
     * @param id 车辆id
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Long id) {
        return carService.delete(id);
    }

    /**
     * 获取车辆列表
     *
     * @param queryDTO 查询条件
     * @return 车辆列表
     */
    @PostMapping("/list")
    public List<CarDTO> findAll(@RequestBody CarDTO queryDTO) {
        List<CarPO> carPOList = carService.list(queryDTO);
        return carPOList.stream().map(po -> {
            CarDTO dto = new CarDTO();
            BeanUtils.copyProperties(po, dto);
            return dto;
        }).collect(Collectors.toList());
    }

    /**
     * 新增车辆
     *
     * @param po 车辆信息
     * @return 操作结果
     */
    @PostMapping
    public Boolean save(@RequestBody CarPO po) {
        return carService.saveAndUpdate(po);
    }

    /**
     * 更新车辆信息
     *
     * @param id 车辆id
     * @param po 车辆信息
     * @return 操作结果
     */
    @PutMapping("/{id}")
    public Boolean update(@PathVariable Long id, @RequestBody CarPO po) {
        po.setId(id);
        return carService.saveAndUpdate(po);
    }
}
